def candy(ratings):
    n=len(ratings)
    left = [1] * n
    right = left[:]
    count=0
    #左遍历，保证左规则，即当前元素大于左边元素，就分配+1
    for i in range(1, n):
        if ratings[i] > ratings[i - 1]:
            left[i] = left[i - 1] + 1

    #右遍历，保证右规则，即当前元素大于右边元素，就分配 + 1
    for i in range(n - 2, -1, -1):
        if ratings[i] > ratings[i + 1]:
            right[i] = right[i + 1] + 1

    #满足左右规则最大值，则为最少分配糖果数
    for i in range(n):
        count += max(left[i], right[i])
    return count

if __name__ =='__main__':
    print(candy([4,4,8,3,1]))